package com.spark.lola.support.wms.job;

import com.spark.lola.feign.service.PortalServiceOpenApi;
import com.spark.lola.support.common.entity.ShiroUser;
import com.spark.lola.support.wms.cache.CollectionCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * wms定时任务
 * @Author: DengYeJun
 * @Date: 2020/4/29 10:27
 */
public class WmsJob {
    private Logger logger = LoggerFactory.getLogger(WmsJob.class);
    private PortalServiceOpenApi portalServiceOpenApi;

    public WmsJob(PortalServiceOpenApi portalServiceOpenApi){
        this.portalServiceOpenApi = portalServiceOpenApi;
        try{
            refreshEmployees();
        }
        catch (Exception e){
            logger.error("获取员工列表失败【{}】",e.getMessage(),e);
        }
    }

    /**
     * 定时策略
     */
    @Scheduled(cron = "0 0/1 * * * ?")
    public void refreshEmployees() {
        logger.info("===更新员工缓存===START===");
        List<ShiroUser> users = portalServiceOpenApi.findAllUser();
        if (CollectionUtils.isEmpty(users)) {
            return;
        }
        CollectionCache.employees.clear();
        CollectionCache.dutyEmployees.clear();
        users.forEach(o -> {
            CollectionCache.employees.put(o.getId(), o);
            List<ShiroUser> shiroUsers = new ArrayList<>();
            if(CollectionCache.dutyEmployees.containsKey(o.getDutyId())) {
                shiroUsers = CollectionCache.dutyEmployees.get(o.getDutyId());
            }
            shiroUsers.add(o);
            CollectionCache.dutyEmployees.put(o.getDutyId(),shiroUsers);
        });
        logger.info("===更新员工缓存===END===");
    }
}
